<template>
    <div class="tableList">
        <el-table :data="tableData" border style="width: 100%;" @sort-change="handleSortChange"
            :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
            :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400,padding:'4px 0'}" @cell-click="cellClick"
            v-loading="loading" element-loading-text="加载中" element-loading-background="rgba(250, 250, 250, 0.5)"
            element-loading-spinner="el-icon-loading" @selection-change="handleSelectionChange" :row-key="getRowKeys"
            ref="tabList" :key="toUpdateTableKey">
            <el-table-column type="selection" width="55" :reserve-selection='true'>
            </el-table-column>
            <el-table-column v-for="(item,index) in tableGroup" :key="item.label" :label="item.name"
                :sortable="item.sortable" :min-width="item.width"
                :show-overflow-tooltip="item.label != 'distributionName'">
                <template slot-scope="scope">
                    <code v-if="item.label == 'processState'">
                        {{state[scope.row[item.label]]}}
                    </code>

                    <code v-else-if="item.label == 'workOrderCode'">
                        <span style="cursor: pointer;"
                            :style="{color:computedColor(scope.row)}">{{scope.row[item.label]}}</span>
                    </code>
                    <!-- 
                        未开始，执行中 报工权限--所有人 || 含有当前用户     显示 + 按钮
                        已结束 报工权限--所有人 || 含有当前用户    显示 + 按钮  按钮被禁用
                        报工权限 非所有人 ，权限用户中无当前用户 显示  -
                    -->
                    <code class="distributionName" v-else-if="item.label == 'distributionName'">
                        <div class="hasPermission" v-show="scope.row.distributionFlag">
                            <div class="disName" v-show="!scope.row.distribute">
                                <el-tooltip class="item" effect="dark" placement="top" popper-class='distribution'>
                                    <div slot="content">{{scope.row[item.label]}}</div>
                                    <span>{{scope.row[item.label]}}</span>
                                </el-tooltip>
                                <el-button icon="el-icon-circle-plus-outline" type="text"
                                    :disabled="scope.row.processState == 2"
                                    @click="changePerson(scope.row,scope.$index)"></el-button>
                            </div>
                            <a-select v-model="selectIds"  placeholder="请选择" :ref="'select' + scope.$index"
                                mode="multiple" v-show="scope.row.distribute" style="width:100%" @blur="handleBlur">
                                <a-select-option v-for="item in userOptions" :key="item.id">
                                    {{item.name}}
                                </a-select-option>
                            </a-select>
                        </div>
                        <span v-show="!scope.row.distributionFlag" style="margin-left:5px">-</span>
                    </code>

                    <code v-else-if="item.label == 'processCode'">
                        {{scope.row[item.label]}}
                        <div class="status" v-if="scope.row.isDelay == 1">延期</div>
                    </code>
                    <code v-else>
                        <code v-if='customImgSet(item.label, scope.row)'>
                            <p v-if='(JSON.parse(scope.row[item.label])).length <= 2'>
                                <img :src="$global.uploadUrl + k.url" alt=""
                                    v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i" class="customImg"
                                    @click='costomImgPreview(i+1, (JSON.parse(scope.row[item.label])).length, JSON.parse(scope.row[item.label]))'>
                            </p>
                            <p v-else>
                                <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[0].url" alt=""
                                    class="customImg"
                                    @click='costomImgPreview(1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                <span class='customImgMoreBox'>
                                    <div class='customImgMore'
                                        @click='costomImgPreview(2, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))'>
                                        <el-popover placement="top" max-width="400" trigger="hover">
                                            <div class='customImgMore' slot="reference">
                                                +{{ JSON.parse(scope.row[item.label]).length - 2 }}</div>
                                            <img :src="$global.uploadUrl + k.url" alt=""
                                                v-for="(k, i) in JSON.parse(scope.row[item.label])" :key="i"
                                                style="margin-right:10px" width='60px' height='60px'
                                                @click="costomImgPreview(i+1, JSON.parse(scope.row[item.label]).length, JSON.parse(scope.row[item.label]))">
                                        </el-popover>
                                    </div>
                                    <img :src="$global.uploadUrl + JSON.parse(scope.row[item.label])[1].url" alt=""
                                        class="customImg">
                                </span>
                            </p>
                        </code>
                        <code v-else>
                            <div v-if="customSelectSet(item.label, scope.row)">
                                <span v-for="(k, j) in customSelectList(item.label, scope.row)" :key="j"
                                    :style="customSelectStyle(item.label, scope.row, k)" class="customSelect">
                                    {{ k }}
                                </span>
                            </div>
                            <div v-else>
                                {{scope.row[item.label]}}
                            </div>
                        </code>
                    </code>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                    <el-button @click="watch(scope.row.id)" type="text" size="small">查看
                    </el-button>
                    <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
                    <el-popconfirm placement='top' confirm-button-text='删除' @confirm='confirmDel(scope.row.id)' title="确认删除任务？
                            操作将同时删除关联的报工，删除后不可恢复">

                        <el-button slot="reference" type="text" size="small" style="margin-left:10px">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
            <div slot="empty">
                <el-empty :image-size='100'></el-empty>
            </div>
        </el-table>
        <el-pagination v-if="tableData.length" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :page-sizes="[10,20,50,100]" :page-size="searchForm.limit" layout="total,prev, pager, next,sizes,jumper"
            :total="total" background :current-page="currentPage">
        </el-pagination>
        <el-dialog :title="customImgData.title" :visible.sync="customImgData.visible" width='68%'>
            <el-carousel trigger="click" height="50vh" :autoplay='false' :initial-index='customImgData.initial'
                @change='handleCarousel' ref='carousel'>
                <el-carousel-item v-for="(item, i) in customImgData.list" :key="i">
                    <img :src="item.url" alt="" class='carouselImg'>
                </el-carousel-item>
            </el-carousel>
            <div class='imgDownLoad' @click='imgDownLoad'>
                <span class='el-icon-download'></span>
                下载
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {
        missionList,
        missionDel,
        userListByProcessId,
        missionEdit
    } from '@/api/produceController'
    import {
        exportTable
    } from "@/mixin"
    export default {
        data() {
            return {
                tableData: [],
                toUpdateTableKey:false,
                loading: false,
                multipleSelection: [],
                total: 0,
                currentPage: 0,
                state: {
                    0: '未开始',
                    1: '执行中',
                    2: '已结束'
                },
                userOptions: [],
                list: [],
                selectIds: [],
                defaultSelectValue:[],
                rowId: '',
                plusShowIndex:0,
                customImgData: {
                    visible: false,
                    list: [],
                    title: '',
                    initial: 0,
                    num: 0
                },
            }
        },
        props: {
            tableGroup: {
                type: Array,
                default: () => []
            },
            searchForm: {
                type: Object,
                default: () => ({})
            }
        },
        computed: {
            computedColor() {
                const color = {
                    0: 'rgb(255,153,0)',
                    1: 'rgb(2, 185, 128)',
                    2: 'rgb(24, 145, 255)'
                }
                return row => {
                    return color[row.processState]
                }
            }
        },
        mixins: [exportTable],
        methods: {
            //任务列表
            getMissionList(data) {
                this.loading = true
                missionList(data).then(res => {
                    if (res.code == 200) {
                        this.tableData = res.data.listData.records
                        this.total = res.data.listData.total
                        this.tableData.map((item, i) => {
                            item.index = (res.data.listData.current - 1) * 10 + (i + 1)
                            if (item.customFieldVos != null) {
                                item.customFieldVos.map(k => {
                                    item[k.customFieldId] = k.value,
                                        item.customType = k.customFieldMess.fieldType
                                })
                            }
                        })
                    }
                    this.loading = false
                    this.currentPage = this.searchForm.page
                    this.$emit('getTotal', res.data.listData.total)
                    this.$emit('getSecondGroupInfo',{
                        key:res.data.secondGroupColumnName,
                        typeCountData:res.data.typeCountData
                    })
                })
            },
            //任务删除
            getMissionDel(data) {
                missionDel(data).then(res => {
                    if (res.code == 200) {
                        let toggleIndex = this.multipleSelection.findIndex(i => i.id == data.id)
                        toggleIndex != -1 && this.multipleSelection.splice(toggleIndex, 1)
                        if (!this.multipleSelection.length) this.$refs.tabList.clearSelection()
                        this.getMissionList(this.searchForm)
                        this.utils.showMsg('删除成功', 'success')
                    }
                })
            },
            clearSelection() {
                this.$refs.tabList.clearSelection()
            },
            handleSortChange({
                order,
                prop
            }) {},
            handleSelectionChange(selection) {
                this.multipleSelection = selection
                let ids = ''
                ids = selection.map(i => i.id).toString()
                this.$emit('getCheckedId', ids)
            },
            getRowKeys(row) {
                return row.id
            },
            //跳转至工单详情页面
            cellClick(row, column) {
                if (column.label == '工单编号') {
                    this.$store.commit('setPage', this.searchForm.page);
                    this.$store.commit('setRouter', this.$route.path);
                    this.$router.push({
                        path: '/productionManagement/edit',
                        query: {
                            id: row.workOrderId,
                            code: row.workOrderCode,
                            state: row.processState
                        }
                    })
                }
            },
            //分配列表+
            changePerson(row, index) {
                this.plusShowIndex ++ 
                if(this.plusShowIndex >= 2) return  //解决用户连续点击多个分配列表+号的行为
                const { id } = row
                this.rowId = id
                if(row.distributionList !== '' && row.distributionList !== null){
                    this.selectIds = row.distributionList.split(',').map(Number)
                }
                row.distribute = true
                this.$nextTick(()=>{ //默认获取焦点 autofocus 配置不生效
                    this.$refs['select' + index][0].focus()
                })
                this.getUserListByProcessId({id})
            },
            handleBlur() {
                this.getMissionEdit({
                    ids: this.rowId,
                    distributions: "",
                    userIds: this.selectIds.toString()
                })
            },
            //编辑用户列表
            getMissionEdit(data) {
                missionEdit(data).then(res => {
                    if (res.code == 200) {
                        this.selectIds = []
                        this.plusShowIndex = 0
                        this.$emit('updateList')
                    }
                })
            },
            //用户列表
            getUserListByProcessId: async function (data) {
                const res = await userListByProcessId(data)
                if (res.code == 200) {
                    this.userOptions = res.data
                }
            },
            //查看
            watch(id) {
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path: '/productionManagement/task/detail',
                    query: {
                        id
                    }
                })
            },
            //删除
            confirmDel(id) {
                this.getMissionDel({
                    id
                })
                let totalPage = Math.ceil((this.total - 1) / this.searchForm.limit)
                let currentPage = this.searchForm.page > totalPage ? totalPage : this.searchForm.page
                this.searchForm.page = currentPage < 1 ? 1 : currentPage
            },
            //编辑
            edit(id) {
                this.$store.commit('setPage', this.searchForm.page);
                this.$store.commit('setRouter', this.$route.path);
                this.$router.push({
                    path: '/productionManagement/task/edit',
                    query: {
                        id
                    }
                })
            },
            // 自定义字段 复选框/单选框 列
            customSelectSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if ((item.customFieldMess.fieldType == 'selectRadio' || item.customFieldMess
                                    .fieldType == 'selectChecked') && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            customSelectList(t, d) {
                let data = []
                try {
                    data = JSON.parse(d[t])
                } catch {
                    data = d[t].split(',')
                    data[0] == '' ? data = [] : ''
                }
                data === Number(data) ? data = [data] : ''
                return data
            },
            customSelectStyle(t, d, v) {
                let style = {}
                if (d.customFieldVos != null) {
                    let obj = d.customFieldVos.find(res => {
                        return res.customFieldId == t
                    })
                    if (obj.value != '' && obj.value != '[]') {
                        if (obj.customFieldMess.fieldType == 'selectRadio') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return obj.value == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                        if (obj.customFieldMess.fieldType == 'selectChecked') {
                            let color = JSON.parse(obj.customFieldMess.checkBox).find(res => {
                                return v == res.value
                            })
                            if (color != undefined) {
                                return {
                                    color: color.color,
                                    background: (color.color).substr(0, 3) + 'a' + (color.color).substr(3, color.color
                                        .length - 4) + ', .1)'
                                }
                            } else {
                                return {
                                    color: '#333',
                                    background: '#f4f4f5'
                                }
                            }
                        }
                    }
                }
            },
            // 自定义字段图片列
            customImgSet(t, d) {
                let state = false
                if (d.customFieldVos != null) {
                    d.customFieldVos.map(item => {
                        if (item.customFieldMess != null) {
                            if (item.customFieldMess.fieldType == 'picture' && t == item.customFieldId) {
                                state = true
                            }
                        }
                    })
                    return state
                } else {
                    return false
                }
            },
            // 自定义图片预览
            costomImgPreview(i, len, list) {
                this.customImgData.visible = true
                this.customImgData.title = '预览' + ' (' + i + '/' + len + ')'
                this.customImgData.initial = Number(i) - 1
                this.customImgData.list = list.map(item => {
                    return {
                        name: item.name,
                        url: this.$global.uploadUrl + item.url
                    }
                })
                this.customImgData.num = i - 1
                this.setActiveItem(i - 1)
            },
            setActiveItem(i) {
                if (this.$refs.carousel) {
                    this.$refs.carousel.setActiveItem(i)
                }
            },
            // 图片预览轮播切换
            handleCarousel(v) {
                this.customImgData.title = '预览' + ' (' + (Number(v) + 1) + '/' + this.customImgData.list.length + ')'
                this.customImgData.num = v
            },
            // 图片下载
            imgDownLoad() {
                window.open(this.customImgData.list[this.customImgData.num].url, "_blank");
            },
            //pageSize 改变时会触发
            handleSizeChange(val) {
                this.searchForm.limit = val
                this.getMissionList(this.searchForm)
            },
            //currentPage 改变时会触发
            handleCurrentChange(val) {
                this.searchForm.page = val
                this.getMissionList(this.searchForm)
            },
            updateTable() {
                this.toUpdateTableKey = !this.toUpdateTableKey
            }
        },
        beforeUpdate() {
            this.$nextTick(() => {
                this.$refs.tabList.doLayout()
            })
        }
    }
</script>

<style lang="less" scoped>
    .tableList {
        padding: 0 20px;

        code {
            font-family: sans-serif;
        }

        .status {
            width: 28px;
            background-color: rgb(255, 59, 48);
            font-size: 12px;
            text-align: center;
            color: white;
            border-radius: 3px;
        }

        .distributionName {
            .hasPermission {
                .disName {
                    display: flex;
                    align-items: center;

                    span {
                        flex-shrink: 0;
                        max-width: 240px;
                        overflow: hidden;
                        white-space: nowrap;
                        display: inline-block;
                        text-overflow: ellipsis;
                    }

                    .el-button.el-button--text {
                        font-size: 16px;
                    }
                }
            }

            .el-select {
                width: 100%;
            }
        }
    }
</style>